import { useState } from 'react'
export default function TodoList() {
    let [todo, setTodo] = useState('')
    let [list, setList] = useState([])
    let addTodo = () => {
        if (!todo.trim()) {
            alert('数据不能为空')
            return;
        }
        setList([...list, { id: Date.now(), title: todo }]);
        setTodo('')
    }
    let delTodo = (id) => {
        setList(list.filter((item) => item.id !== id))
    }
    let addKeyCode = (e) => {
        if (e.keyCode === 13) {
            addTodo()
        }
    }
    return (
        <div>
            <input type="text" value={todo}
                onChange={e => setTodo(e.target.value)}
                onKeyDown={e => addKeyCode(e)}
            />
            <button onClick={addTodo}>添加</button>
            <hr />
            <div>
                {
                    list.map((item) => (
                        <li key={item.id}>
                            {item.id}---{item.title}
                            <button onClick={() => { delTodo(item.id) }}>删除</button>
                        </li>
                    ))
                }
            </div>
        </div>
    )
}